package org.easyx.ui.controller.sys;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.easyx.core.ui.easyui.EasyUITree;
import org.easyx.core.ui.easyui.PageBean;
import org.easyx.core.ui.easyui.PageParam;
import org.easyx.core.utils.ObjKit;
import org.easyx.ser.sys.entity.SysRole;
import org.easyx.ser.sys.entity.SysRoleResource;
import org.easyx.ser.sys.serivce.SysRoleResourceService;
import org.easyx.ser.sys.serivce.SysRoleService;
import org.easyx.ui.base.BossEasyUIBaseController;
import org.easyx.ui.base.BossEasyUISessionUser;
import org.easyx.ui.util.SessionKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-14
 */
@Controller
@RequestMapping("/sys/sysRole")
public class SysRoleController extends BossEasyUIBaseController {
	private static final Logger log = LoggerFactory.getLogger(SysRoleController.class);
	private static final String basePagePath = "sys/role/";
	
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleResourceService sysRoleResourceService;
	
	@RequestMapping("currentUserRolePage")
	public String currentUserRolePage(){
		return "sys/role/currentUserRole";
	}
	
	@RequestMapping("currentUserRole")
	public @ResponseBody Object currentUserRole(){
		BossEasyUISessionUser su = SessionKit.getSessionUser(request);
		List<SysRole> list = sysRoleService.selectListByUserId(su.getUserId());
		PageParam pageParam = new PageParam();
		pageParam.setPage(1);
		pageParam.setRows(1000);
		pageParam.setOrder("asc");
		pageParam.setSort("seq");
		PageBean<SysRole> pageBean = new PageBean<>(pageParam);
		pageBean.setTotal(list.size());
		pageBean.setRows(list);
		return pageBean;
	}
	
	/**
	 * 用户-角色选择树
	 */
	@RequestMapping("/tree")
	public @ResponseBody Object tree(){
		List<SysRole> list = sysRoleService.selectList(new EntityWrapper<SysRole>().orderBy("seq", true));
		List<EasyUITree> tree = new ArrayList<EasyUITree>();
		for(int i=0;list!=null && i<list.size();i++){
			EasyUITree t = new EasyUITree();
			t.setId(list.get(i).getId());
			t.setText(list.get(i).getName());
			
			tree.add(t);
		}
		
		return tree;
	}
	
	@RequestMapping("/findResourceIdListByRoleId")
	public @ResponseBody Object findResourceIdListByRoleId(Long id){
		List<SysRoleResource> list = sysRoleResourceService.selectList(new EntityWrapper<SysRoleResource>().eq("roleId",id));
		List<Long> l = new ArrayList<Long>();
		for(SysRoleResource r:list){
			l.add(r.getResourceId());
		}
		
		return operateSuccess("数据获取成功", l);
	}
	
	/**
	 * 进入角色资源授权页面
	 */
	@RequiresPermissions("sys/sysRole/grant")
	@RequestMapping("/grantPage")
	public String grantPage(Long id){
		this.request.setAttribute("id", id);
		return basePagePath+"roleGrant";
	}
	
	/**
	 * 提交角色资源授权信息
	 */
	@RequiresPermissions("sys/sysRole/grant")
	@RequestMapping("/grant")
	public @ResponseBody Object grant(Long id,String resourceIds){
		try {
			SysRole role = sysRoleService.selectById(id);
			if(ObjKit.isEmpty(role)){
				return operateError("角色ID【"+id+"】对应的角色数据获取异常，请联系管理员!");
			}
			
			sysRoleService.updateRoleResource(id,resourceIds);

			return operateSuccess("授权成功!");
		} catch (Exception e) {
			log.error("未知错误", e);
			return operateError();
		}
	}
	
	/**
	 * 进入列表页面
	 */
	@RequiresPermissions("sys/sysRole/manager")
	@RequestMapping("/manager")
	public String manager(Model model){
		BossEasyUISessionUser su = SessionKit.getSessionUser(request);
		model.addAttribute("sessionUser", su);
		
		return basePagePath+"list";
	}
	
	/**
	 * 查询列表数据(分页)
	 */
	@RequiresPermissions("sys/sysRole/manager")
	@RequestMapping("/dataGrid")
	public @ResponseBody Object dataGrid(PageParam pageParam, SysRole entity){
		PageBean<SysRole> pageBean = this.selectListPage(pageParam, entity, sysRoleService);
		return pageBean;
	}
	
	/**
	 * 转到添加页面 
	 */
	@RequiresPermissions("sys/sysRole/add")
	@RequestMapping("/addPage")
	public String addPage(){
		return basePagePath+"add";
	}
	
	/**
	 * 保存 .
	 */
	@RequiresPermissions("sys/sysRole/add")
	@RequestMapping("/add")
	public @ResponseBody Object add(@Valid SysRole entity, BindingResult result, String roleIds) {
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			/** 数据唯一性校验 */
			
			addOptions(entity);
			//插入数据库
			sysRoleService.insert(entity);
			
			return operateSuccess("添加成功!");
		} catch (Exception e) {
			log.error("保存添加的数据，出现异常:", e);
			return operateError("添加失败!");
		}
	}
	
	/**
	 * 转到修改页面 .
	 */
	@RequiresPermissions("sys/sysRole/edit")
	@RequestMapping("/editPage")
	public String editPage(Model model, Long id) {
		try {
			SysRole entity = sysRoleService.selectById(id);
			if (ObjKit.isEmpty(entity)) {
				log.error("进入编辑页面时，获取想要修改的数据为空！id="+id);
			}

			model.addAttribute("entity",entity);
		} catch (Exception e) {
			log.error("进入编辑页面时，获取想要修改的数据出现异常:id="+id, e);
		}
		return  basePagePath+"edit" ;
	}
	
	/**
	 * 保存修改后的信息 .
	 */
	@RequiresPermissions("sys/sysRole/edit")
	@RequestMapping("/edit")
	public @ResponseBody Object edit(@Valid SysRole entity, BindingResult result) {
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			Long id = entity.getId();
			SysRole oldObj = sysRoleService.selectById(id);
			if (ObjKit.isEmpty(oldObj)) {
				return operateError("保存修改的数据时，无法获取想要修改的数据，id="+id);
			}
			
			/** 数据唯一性校验逻辑*/
			
			
			//更新数据库
			sysRoleService.updateById(entity);
			
			return operateSuccess("修改成功!");
		} catch (Exception e) {
			log.error("保存修改的数据时，出现异常:", e);
			return operateError("修改失败!");
		}
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("sys/sysRole/delete")
	@RequestMapping("/delete")
	public @ResponseBody Object delete(Long id) {
		try {
			SysRole entity = sysRoleService.selectById(id);
			if (ObjKit.isEmpty(entity)) {
				return operateError("删除数据时，无法获取想要删除的数据，id="+id);
			}
			
			sysRoleService.deleteById(id);
			
			return operateSuccess("删除成功!");
		} catch (Exception e) {
			log.error("删除数据时，出现异常:id="+id, e);
			return operateError("删除失败!");
		}
	}
	
}
